using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Splines;
using UnityEngine.EventSystems;
using UnityEngine;
using TMPro;

public class HandView : MonoBehaviour
{
    [Header("组件引用")]
    public CardManager cardManager;
    public Transform cardContainer;
    public GameObject cardViewPrefab;
    public SplineContainer splineContainer;


    [Header("调试设置")]
    public bool enableDebug = true;

    private List<CardView> _currentHandCardViews = new List<CardView>();
    private bool _isInitialized = false;

    void Start()
    {
        InitializeHandView();
    }

    /// <summary>
    /// 初始化手牌视图
    /// </summary>
    private void InitializeHandView()
    {
        if (_isInitialized) return;

        // 自动查找缺失的引用
        if (cardManager == null)
        {
            cardManager = FindObjectOfType<CardManager>();
            if (cardManager == null)
            {
                Debug.LogError("HandView: 未找到CardManager！");
                return;
            }
        }

        if (splineContainer == null)
        {
            splineContainer = GetComponentInChildren<SplineContainer>();
            if (splineContainer == null)
            {
                Debug.LogError("HandView: 未找到SplineContainer！");
                return;
            }
        }

        if (cardContainer == null)
        {
            cardContainer = transform;
        }

        // 检查事件订阅前的状态
        int beforeSubscribeCount = cardManager.OnHandChanged?.GetInvocationList()?.Length ?? 0;
        Debug.Log($"HandView: 订阅前OnHandChanged订阅者数量: {beforeSubscribeCount}");

        // 订阅事件
        cardManager.OnHandChanged += OnHandChanged;
        _isInitialized = true;

        // 检查事件订阅后的状态
        int afterSubscribeCount = cardManager.OnHandChanged?.GetInvocationList()?.Length ?? 0;
        Debug.Log($"HandView: 订阅后OnHandChanged订阅者数量: {afterSubscribeCount}");


        Debug.Log("HandView 初始化完成，已订阅OnHandChanged事件");

        // 立即显示当前手牌（如果有的话）
        if (cardManager.hand.Count > 0)
        {
            Debug.Log($"立即显示现有手牌: {cardManager.hand.Count}张");
            OnHandChanged(cardManager.hand);
        }
    }

    private void OnHandChanged(List<Card> handCards)
    {
        Debug.Log($"=== HandView.OnHandChanged 被调用 ===");
        if (handCards == null)
        {
            Debug.Log("收到的手牌列表为null");
            return;
        }

        Debug.Log($"收到手牌变化事件，卡牌数量: {handCards.Count}");

        // 使用协程处理手牌更新
        StartCoroutine(ProcessHandChange(handCards));
    }

    /// <summary>
    /// 处理手牌变化
    /// </summary>
    private IEnumerator ProcessHandChange(List<Card> newHandCards)
    {
        // 等待一帧，确保所有操作完成
        yield return null;

        // 清理现有的CardView
        ClearHandUI();

        Debug.Log($"开始创建 {newHandCards.Count} 张卡牌视图");

        // 为每张卡创建CardView
        foreach (Card card in newHandCards)
        {
            CreateCardView(card);
        }

        Debug.Log($"创建完成，当前CardView数量: {_currentHandCardViews.Count}");

        // 更新卡牌位置
        yield return StartCoroutine(UpdateCardPositionsWithAnimation());
    }


    /// <summary>
    /// 创建卡牌视图
    /// </summary>
    private void CreateCardView(Card card)
    {
        GameObject cardViewObj = Instantiate(cardViewPrefab, cardContainer);
        CardView cardView = cardViewObj.GetComponent<CardView>();

        if (cardView != null)
        {
            cardView.Initialize(card);
            _currentHandCardViews.Add(cardView);
        }
    }

    /// <summary>
    /// 清理手牌UI
    /// </summary>
    private void ClearHandUI()
    {
        foreach (CardView cardView in _currentHandCardViews)
        {
            if (cardView != null)
            {
                cardView.transform.DOKill();
                Destroy(cardView.gameObject);
            }
        }
        _currentHandCardViews.Clear();
    }

    /// <summary>
    /// 处理CardView列表
    /// </summary>
    private IEnumerator UpdateCardPositionsWithAnimation()
    {
        if (_currentHandCardViews.Count == 0)
        {
            yield break;
        }

        // 等待一帧确保所有CardView已实例化
        yield return null;

        float cardSpacing = 1f / 10f;
        float firstCardPosition = 0.5f - (_currentHandCardViews.Count - 1) * cardSpacing / 2;
        Spline spline = splineContainer.Spline;

        // 获取SplineContainer的世界变换
        Transform splineTransform = splineContainer.transform;

        // 调试：显示样条位置信息
        Debug.Log($"样条容器位置: {splineTransform.position}");
        Debug.Log($"手牌视图位置: {transform.position}");
        Debug.Log($"卡牌数量: {_currentHandCardViews.Count}");

        for (int i = 0; i < _currentHandCardViews.Count; i++)
        {
            if (_currentHandCardViews[i] == null) continue;

            float p = firstCardPosition + i * cardSpacing;
            p = Mathf.Clamp01(p); // 确保在0-1范围内

            // 获取样条上的局部坐标
            Vector3 localSplinePosition = spline.EvaluatePosition(p);
            Vector3 forward = spline.EvaluateTangent(p);
            Vector3 up = spline.EvaluateUpVector(p);

            // 将局部坐标转换为世界坐标
            Vector3 worldSplinePosition = splineTransform.TransformPoint(localSplinePosition);

            // 计算旋转（修正版本）
            Quaternion rotation = Quaternion.identity;

            // 添加深度偏移避免Z-fighting
            Vector3 finalPosition = worldSplinePosition + 0.01f * i * Vector3.back;

            // 调试：显示每张卡的位置信息
            Debug.Log($"卡牌 {i}: 样条进度={p}, 局部位置={localSplinePosition}, 世界位置={worldSplinePosition}");

            // 执行动画
            _currentHandCardViews[i].transform.position = finalPosition;
            _currentHandCardViews[i].transform.rotation = Quaternion.identity;
        }

        yield return new WaitForSeconds(0.15f + (_currentHandCardViews.Count * 0.05f));
        Debug.Log("手牌布局动画完成");
    }


    /// <summary>
    /// 手动测试手牌更新
    /// </summary>
    [ContextMenu("测试手牌更新")]
    public void TestHandUpdate()
    {
        Debug.Log("手动测试手牌更新");
        if (cardManager != null && cardManager.hand.Count > 0)
        {
            OnHandChanged(cardManager.hand);
        }
    }

    private void OnDestroy()
    {
        // 清理事件订阅
        if (cardManager != null)
        {
            cardManager.OnHandChanged -= OnHandChanged;
        }

        // 清理所有动画
        foreach (CardView cardView in _currentHandCardViews)
        {
            if (cardView != null)
            {
                cardView.transform.DOKill();
            }
        }
    }
}
